//
//  AFNetWorkService.m
//  TBRJL
//
//  Created by 程三 on 15/6/10.
//  Copyright (c) 2015年 程三. All rights reserved.
//

#import "AFNetWorkService.h"
#import "AFHTTPRequestOperationManager.h"
#import "Reachability.h"
#import "AFURLSessionManager.h"


@implementation AFNetWorkService

- (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"HNZS" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];

    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}



-(void)requestWithServiceName:(NSString *)serviceName
                       params:(NSMutableDictionary *)params
                   httpMethod:(NSString *)httpMethod
           resultIsDictionary:(BOOL)resultIsDictionary
                completeBlock:(RequestCompelete)block
{ 
    
    NSString *serviceUrl = (NSString *)[Util getValue:@"baseurl"];
    if (!serviceUrl) {
        serviceUrl = ServiceURL;
    }
    if ([serviceName isEqualToString:@"appsearchpromenue"]) {
        serviceUrl = ServiceURL;
    }
    //拼接URL
    NSString *url = [NSString stringWithFormat:@"%@%@/query",serviceUrl,serviceName];
   
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<>+"].invertedSet];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    if(!resultIsDictionary)
    {
        manager.responseSerializer = [AFCompoundResponseSerializer serializer];//响应
    }
    else
    {
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
//    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    manager.requestSerializer.timeoutInterval = 20;
    
    //设置相应内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    
    
    //处理POST的参数
    NSComparisonResult compareRet = [httpMethod caseInsensitiveCompare:@"POST"];
    if(NSOrderedSame == compareRet)
    {
        [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             
             if(block != nil)
             {
                 
                 block(resultIsDictionary ? resultDic:operation.responseString);
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             
             NSLog(@"%zd",error.code);
             if (error.code == -1001) {
                 [MBProgressHUD hideHUD];
                 
                 static dispatch_once_t onceToken;
                 dispatch_once(&onceToken, ^{
                      [MBProgressHUD showError:@"网络超时"];
                 });
          
                 return ;
             }
             
             [self afn];
             
             NSLog(@"调用服务出错(POST)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
    else
    {
        [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             if(block != nil)
             {
                 block(resultIsDictionary ? resultDic:operation.responseString);
                 
             }
         }
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
            [self afn];
             NSLog(@"调用服务出错(GET)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
}





-(void)RequestWithServiceName:(NSString *)serviceName
                       params:(NSMutableDictionary *)params
                   httpMethod:(NSString *)httpMethod
           resultIsDictionary:(BOOL)resultIsDictionary
                completeBlock:(RequestCompelete)block
{

    NSString *  url = [NSString stringWithFormat:@"https://henan.qichedangan.cn/restservices/appgetversion/%@/query",serviceName];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<>+"].invertedSet];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    if(!resultIsDictionary)
    {
        manager.responseSerializer = [AFCompoundResponseSerializer serializer];//响应
    }
    else
    {
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
//    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    //设置相应内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    
    
    //处理POST的参数
    NSComparisonResult compareRet = [httpMethod caseInsensitiveCompare:@"POST"];
    if(NSOrderedSame == compareRet)
    {
        [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             
             if(block != nil)
             {
                 
                 block(resultIsDictionary ? resultDic:operation.responseString);
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
              [self afn];
             NSLog(@"调用服务出错(POST)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
    else
    {
        [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             if(block != nil)
             {
                 block(resultIsDictionary ? resultDic:operation.responseString);
                 
             }
         }
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
            [self afn];
             NSLog(@"调用服务出错(GET)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
}




-(void)ChangePwdWithServiceName:(NSString *)serviceName
                       params:(NSMutableDictionary *)params
                   httpMethod:(NSString *)httpMethod
           resultIsDictionary:(BOOL)resultIsDictionary
                completeBlock:(RequestCompelete)block
{
    
    NSString *serviceUrl = (NSString *)[Util getValue:@"baseurl"];
    if (!serviceUrl) {
        serviceUrl = ServiceURL;
    }
    //拼接URL
    NSString *url = [NSString stringWithFormat:@"%@%@/query",serviceUrl,serviceName];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<>+"].invertedSet];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    if(!resultIsDictionary)
    {
        manager.responseSerializer = [AFCompoundResponseSerializer serializer];//响应
    }
    else
    {
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    //    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    //设置相应内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    
    
    //处理POST的参数
    NSComparisonResult compareRet = [httpMethod caseInsensitiveCompare:@"POST"];
    if(NSOrderedSame == compareRet)
    {
        [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             
             if(block != nil)
             {
                 
                 block(resultIsDictionary ? resultDic:operation.responseString);
             }
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             [self afn];
             NSLog(@"调用服务出错(POST)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
    else
    {
        [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             if(block != nil)
             {
                 block(resultIsDictionary ? resultDic:operation.responseString);
                 
             }
         }
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             [self afn];
             NSLog(@"调用服务出错(GET)");
             if(block != nil)
             {
                 block(nil);
             }
         }];
    }
}






-(NSString*)objectToJson:(NSObject *)object
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}



-(void)afn{
    //1.创建网络状态监测管理者
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    //开启监听，记得开启，不然不走block
    [manger startMonitoring];
    //2.监听改变
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown = -1,
         AFNetworkReachabilityStatusNotReachable = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                [MBProgressHUD showWarning:@"似乎没有网络连接"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G|4G");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi");
                break;
            default:
                break;
        }
    }];
}



//#pragma mark 获取网络状态 0:没有网 1:WI-FI 2:手机移动网
-(int)getNetState
{
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable)
    {
        // 有wifi
        return 1;
    }
    else if ([conn currentReachabilityStatus] != NotReachable)
    {
        // 没有使用wifi, 使用手机自带网络进行上网
        return 2;
    }
    else
    {
        // 没有网络
        return 0;
    }
    
}

@end
